class ChessBoard {
    constructor() {
        this.canvas = document.getElementById('chessboard');
        this.gridSize = 60; // 格子大小
        this.padding = 40; // 统一的边距
        
        // 根据格子大小和边距计算画布尺寸
        this.canvas.width = this.gridSize * 8 + this.padding * 2;  // 8个间隔 + 两边的padding
        this.canvas.height = this.gridSize * 9 + this.padding * 2; // 9个间隔 + 两边的padding
        
        this.ctx = this.canvas.getContext('2d');
        
        // 定义棋子初始布局
        this.pieces = [
            // 红方(下方)
            { type: '车', color: 'red', x: 0, y: 9 },
            { type: '马', color: 'red', x: 1, y: 9 },
            { type: '相', color: 'red', x: 2, y: 9 },
            { type: '仕', color: 'red', x: 3, y: 9 },
            { type: '帅', color: 'red', x: 4, y: 9 },
            { type: '仕', color: 'red', x: 5, y: 9 },
            { type: '相', color: 'red', x: 6, y: 9 },
            { type: '马', color: 'red', x: 7, y: 9 },
            { type: '车', color: 'red', x: 8, y: 9 },
            { type: '炮', color: 'red', x: 1, y: 7 },
            { type: '炮', color: 'red', x: 7, y: 7 },
            { type: '兵', color: 'red', x: 0, y: 6 },
            { type: '兵', color: 'red', x: 2, y: 6 },
            { type: '兵', color: 'red', x: 4, y: 6 },
            { type: '兵', color: 'red', x: 6, y: 6 },
            { type: '兵', color: 'red', x: 8, y: 6 },
            
            // 黑方(上方)
            { type: '车', color: 'black', x: 0, y: 0 },
            { type: '马', color: 'black', x: 1, y: 0 },
            { type: '象', color: 'black', x: 2, y: 0 },
            { type: '士', color: 'black', x: 3, y: 0 },
            { type: '将', color: 'black', x: 4, y: 0 },
            { type: '士', color: 'black', x: 5, y: 0 },
            { type: '象', color: 'black', x: 6, y: 0 },
            { type: '马', color: 'black', x: 7, y: 0 },
            { type: '车', color: 'black', x: 8, y: 0 },
            { type: '炮', color: 'black', x: 1, y: 2 },
            { type: '炮', color: 'black', x: 7, y: 2 },
            { type: '卒', color: 'black', x: 0, y: 3 },
            { type: '卒', color: 'black', x: 2, y: 3 },
            { type: '卒', color: 'black', x: 4, y: 3 },
            { type: '卒', color: 'black', x: 6, y: 3 },
            { type: '卒', color: 'black', x: 8, y: 3 }
        ];
        
        this.selectedPiece = null; // 当前选中的棋子
        this.currentPlayer = 'red'; // 当前回合，红方先手
        
        this.gameOver = false; // 添加游戏结束标志
        this.winner = null; // 添加获胜方
        
        // 添加状态显示区域
        this.statusDiv = document.createElement('div');
        this.statusDiv.className = 'status';
        this.canvas.parentNode.insertBefore(this.statusDiv, this.canvas);
        this.updateStatus();
        
        // 添加鼠标事件监听
        this.canvas.addEventListener('click', this.handleClick.bind(this));
        
        this.ai = new ChessAI(4); // 创建AI实例，搜索深度为4
        
        this.init();
    }

    init() {
        this.drawBoard();
        this.drawPieces();
    }

    drawBoard() {
        const ctx = this.ctx;
        
        // 清空画布
        ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制底色
        ctx.fillStyle = '#ffedcc';
        ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 设置线条样式
        ctx.strokeStyle = '#000';
        ctx.lineWidth = 1;
        
        // 绘制纵向线条（分上下两部分，中间楚河汉界不画）
        for (let i = 0; i < 9; i++) {
            ctx.beginPath();
            if (i === 0 || i === 8) {
                // 边线画完整
                ctx.moveTo(this.padding + i * this.gridSize, this.padding);
                ctx.lineTo(this.padding + i * this.gridSize, this.padding + 9 * this.gridSize);
            } else {
                // 中间的线条分上下两段
                // 上半部分
                ctx.moveTo(this.padding + i * this.gridSize, this.padding);
                ctx.lineTo(this.padding + i * this.gridSize, this.padding + 4 * this.gridSize);
                ctx.stroke();
                
                // 下半部分
                ctx.beginPath();
                ctx.moveTo(this.padding + i * this.gridSize, this.padding + 5 * this.gridSize);
                ctx.lineTo(this.padding + i * this.gridSize, this.padding + 9 * this.gridSize);
            }
            ctx.stroke();
        }
        
        // 绘制横向线条
        for (let i = 0; i < 10; i++) {
            ctx.beginPath();
            ctx.moveTo(this.padding, this.padding + i * this.gridSize);
            ctx.lineTo(this.padding + 8 * this.gridSize, this.padding + i * this.gridSize);
            ctx.stroke();
        }
        
        // 绘制楚河汉界
        ctx.font = '30px KaiTi';
        ctx.fillStyle = '#000';
        ctx.textAlign = 'center'; // 设置文字水平居中
        ctx.textBaseline = 'middle'; // 设置文字垂直居中
        
        // 计算楚河和汉界的位置
        const centerY = this.padding + 4.5 * this.gridSize; // 垂直中心位置
        const leftCenter = this.padding + 2 * this.gridSize; // 左半边中心
        const rightCenter = this.padding + 6 * this.gridSize; // 右半边中心
        
        ctx.fillText('楚 河', leftCenter, centerY);
        ctx.fillText('汉 界', rightCenter, centerY);
        
        // 绘制斜线（九宫格）
        // 上方九宫
        ctx.beginPath();
        ctx.moveTo(this.padding + 3 * this.gridSize, this.padding);
        ctx.lineTo(this.padding + 5 * this.gridSize, this.padding + 2 * this.gridSize);
        ctx.moveTo(this.padding + 5 * this.gridSize, this.padding);
        ctx.lineTo(this.padding + 3 * this.gridSize, this.padding + 2 * this.gridSize);
        ctx.stroke();
        
        // 下方九宫
        ctx.beginPath();
        ctx.moveTo(this.padding + 3 * this.gridSize, this.padding + 7 * this.gridSize);
        ctx.lineTo(this.padding + 5 * this.gridSize, this.padding + 9 * this.gridSize);
        ctx.moveTo(this.padding + 5 * this.gridSize, this.padding + 7 * this.gridSize);
        ctx.lineTo(this.padding + 3 * this.gridSize, this.padding + 9 * this.gridSize);
        ctx.stroke();
        
        // 绘制兵位和炮位的标记
        this.drawPositionMarks();
    }

    drawPositionMarks() {
        // 绘制位置标记（兵位和炮位）
        const positions = [
            // 炮位
            {x: 1, y: 2}, {x: 7, y: 2},
            {x: 1, y: 7}, {x: 7, y: 7},
            // 兵位
            {x: 0, y: 3}, {x: 2, y: 3}, {x: 4, y: 3}, {x: 6, y: 3}, {x: 8, y: 3},
            {x: 0, y: 6}, {x: 2, y: 6}, {x: 4, y: 6}, {x: 6, y: 6}, {x: 8, y: 6}
        ];

        positions.forEach(pos => {
            this.drawPositionMark(pos.x, pos.y);
        });
    }

    drawPositionMark(x, y) {
        const size = 10; // 标记大小
        const ctx = this.ctx;
        const posX = this.padding + x * this.gridSize;
        const posY = this.padding + y * this.gridSize;

        // 绘制四角标记
        ctx.beginPath();
        // 左上
        if (x > 0) {
            ctx.moveTo(posX - 5, posY - size);
            ctx.lineTo(posX - 5, posY - 5);
            ctx.lineTo(posX - size, posY - 5);
        }
        // 右上
        if (x < 8) {
            ctx.moveTo(posX + 5, posY - size);
            ctx.lineTo(posX + 5, posY - 5);
            ctx.lineTo(posX + size, posY - 5);
        }
        // 左下
        if (x > 0) {
            ctx.moveTo(posX - 5, posY + size);
            ctx.lineTo(posX - 5, posY + 5);
            ctx.lineTo(posX - size, posY + 5);
        }
        // 右下
        if (x < 8) {
            ctx.moveTo(posX + 5, posY + size);
            ctx.lineTo(posX + 5, posY + 5);
            ctx.lineTo(posX + size, posY + 5);
        }
        ctx.stroke();
    }

    drawPieces() {
        this.pieces.forEach(piece => {
            this.drawPiece(piece);
        });
    }

    drawPiece(piece) {
        const ctx = this.ctx;
        const x = this.padding + piece.x * this.gridSize;
        const y = this.padding + piece.y * this.gridSize;
        const radius = this.gridSize * 0.45; // 增大棋子尺寸

        // 绘制棋子外圈
        ctx.beginPath();
        ctx.arc(x, y, radius, 0, Math.PI * 2);
        ctx.fillStyle = '#f0d5a0'; // 米黄色底色
        ctx.fill();
        ctx.strokeStyle = '#000';
        ctx.lineWidth = 2;
        ctx.stroke();

        // 绘制内圈
        ctx.beginPath();
        ctx.arc(x, y, radius - 3, 0, Math.PI * 2);
        ctx.strokeStyle = '#4a4a4a';
        ctx.lineWidth = 1;
        ctx.stroke();

        // 绘制棋子文字
        ctx.font = `bold ${Math.floor(radius * 1.2)}px KaiTi`; // 加粗字体，调整字号
        ctx.fillStyle = piece.color === 'red' ? '#c40d0d' : '#000'; // 红色棋子用深红色
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        // 绘制文字阴影效果
        ctx.shadowColor = piece.color === 'red' ? '#600' : '#333';
        ctx.shadowBlur = 2;
        ctx.fillText(piece.type, x, y);
        ctx.shadowBlur = 0; // 重置阴影效果
    }

    handleClick(e) {
        // 如果游戏已结束，不再响应点击
        if (this.gameOver) return;

        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        // 将点击坐标转换为棋盘格子坐标
        const gridX = Math.round((x - this.padding) / this.gridSize);
        const gridY = Math.round((y - this.padding) / this.gridSize);
        
        // 检查是否点击在有效范围内
        if (gridX < 0 || gridX > 8 || gridY < 0 || gridY > 9) return;

        // 查找点击位置的棋子
        const clickedPiece = this.pieces.find(p => p.x === gridX && p.y === gridY);

        if (this.selectedPiece) {
            // 如果已经选中棋子，尝试移动
            if (clickedPiece && clickedPiece.color === this.currentPlayer) {
                // 如果点击同色棋子，更换选中的棋子
                this.selectedPiece = clickedPiece;
            } else if (this.isValidMove(this.selectedPiece, gridX, gridY)) {
                // 如果是有效移动，执行移动
                this.movePiece(this.selectedPiece, gridX, gridY);
                this.selectedPiece = null;
                // 切换回合
                this.currentPlayer = this.currentPlayer === 'red' ? 'black' : 'red';
                
                // 如果轮到黑方（AI），执行AI移动
                if (this.currentPlayer === 'black' && !this.gameOver) {
                    this.statusDiv.textContent = "AI 正在思考...";
                    setTimeout(() => {
                        console.log("AI 开始思考...");
                        const aiMove = this.ai.getBestMove(this);
                        if (aiMove) {
                            console.log(`AI 决定移动 ${aiMove.piece.type} 从(${aiMove.piece.x},${aiMove.piece.y})到(${aiMove.targetX},${aiMove.targetY})`);
                            this.movePiece(aiMove.piece, aiMove.targetX, aiMove.targetY);
                            this.currentPlayer = 'red';
                            this.updateStatus();
                            this.drawBoard();
                            this.drawPieces();
                        }
                    }, 100);
                }
            }
        } else if (clickedPiece && clickedPiece.color === this.currentPlayer) {
            // 选中棋子
            this.selectedPiece = clickedPiece;
        }

        // 重绘棋盘
        this.drawBoard();
        this.drawPieces();
        
        // 如果有选中的棋子，绘制选中效果
        if (this.selectedPiece) {
            this.drawSelectedPiece(this.selectedPiece);
        }

        // 在切换玩家后更新状态
        this.updateStatus();
    }

    drawSelectedPiece(piece) {
        const ctx = this.ctx;
        const x = this.padding + piece.x * this.gridSize;
        const y = this.padding + piece.y * this.gridSize;
        const radius = this.gridSize * 0.45;

        // 绘制选中效果
        ctx.beginPath();
        ctx.arc(x, y, radius + 2, 0, Math.PI * 2);
        ctx.strokeStyle = '#ff0';
        ctx.lineWidth = 2;
        ctx.stroke();
    }

    isValidMove(piece, targetX, targetY) {
        // 检查是否吃自己的子
        const targetPiece = this.pieces.find(p => p.x === targetX && p.y === targetY);
        if (targetPiece && targetPiece.color === piece.color) {
            return false;
        }

        // 根据不同棋子类型检查移动是否合法
        switch (piece.type) {
            case '车':
                return this.isValidRookMove(piece, targetX, targetY);
            case '马':
                return this.isValidKnightMove(piece, targetX, targetY);
            case '相':
            case '象':
                return this.isValidBishopMove(piece, targetX, targetY);
            case '仕':
            case '士':
                return this.isValidGuardMove(piece, targetX, targetY);
            case '帅':
            case '将':
                return this.isValidKingMove(piece, targetX, targetY);
            case '炮':
                return this.isValidCannonMove(piece, targetX, targetY);
            case '兵':
            case '卒':
                return this.isValidPawnMove(piece, targetX, targetY);
            default:
                return false;
        }
    }

    movePiece(piece, targetX, targetY) {
        // 检查是否吃掉将帅
        const targetPiece = this.pieces.find(p => p.x === targetX && p.y === targetY);
        if (targetPiece && (targetPiece.type === '将' || targetPiece.type === '帅')) {
            this.gameOver = true;
            this.winner = piece.color;
        }
        
        // 移除目标位置的棋子（吃子）
        this.pieces = this.pieces.filter(p => !(p.x === targetX && p.y === targetY));
        
        // 移动选中的棋子
        piece.x = targetX;
        piece.y = targetY;
        
        // 更新状态显示
        this.updateStatus();
    }

    // 各种棋子的走法规则实现
    isValidRookMove(piece, targetX, targetY) {
        // 车只能直线移动
        if (targetX !== piece.x && targetY !== piece.y) return false;
        
        // 检查路径上是否有其他棋子
        return !this.hasObstacleBetween(piece, targetX, targetY);
    }

    isValidKnightMove(piece, targetX, targetY) {
        const dx = Math.abs(targetX - piece.x);
        const dy = Math.abs(targetY - piece.y);
        
        // 马走日
        if (!((dx === 1 && dy === 2) || (dx === 2 && dy === 1))) return false;
        
        // 检查马脚
        if (dx === 2) {
            const footX = piece.x + (targetX > piece.x ? 1 : -1);
            return !this.pieces.some(p => p.x === footX && p.y === piece.y);
        } else {
            const footY = piece.y + (targetY > piece.y ? 1 : -1);
            return !this.pieces.some(p => p.x === piece.x && p.y === footY);
        }
    }

    hasObstacleBetween(piece, targetX, targetY) {
        const dx = targetX - piece.x;
        const dy = targetY - piece.y;
        
        if (dx === 0) {
            // 竖直移动
            const step = dy > 0 ? 1 : -1;
            for (let y = piece.y + step; y !== targetY; y += step) {
                if (this.pieces.some(p => p.x === piece.x && p.y === y)) return true;
            }
        } else {
            // 水平移动
            const step = dx > 0 ? 1 : -1;
            for (let x = piece.x + step; x !== targetX; x += step) {
                if (this.pieces.some(p => p.x === x && p.y === piece.y)) return true;
            }
        }
        return false;
    }

    isValidBishopMove(piece, targetX, targetY) {
        const dx = Math.abs(targetX - piece.x);
        const dy = Math.abs(targetY - piece.y);
        
        // 相/象走田字
        if (dx !== 2 || dy !== 2) return false;
        
        // 不能过河
        if (piece.color === 'red' && targetY < 5) return false;
        if (piece.color === 'black' && targetY > 4) return false;
        
        // 检查象眼
        const eyeX = piece.x + (targetX > piece.x ? 1 : -1);
        const eyeY = piece.y + (targetY > piece.y ? 1 : -1);
        return !this.pieces.some(p => p.x === eyeX && p.y === eyeY);
    }

    isValidGuardMove(piece, targetX, targetY) {
        const dx = Math.abs(targetX - piece.x);
        const dy = Math.abs(targetY - piece.y);
        
        // 仕/士走斜线一格
        if (dx !== 1 || dy !== 1) return false;
        
        // 限制在九宫格内
        if (targetX < 3 || targetX > 5) return false;
        if (piece.color === 'red' && (targetY < 7 || targetY > 9)) return false;
        if (piece.color === 'black' && (targetY < 0 || targetY > 2)) return false;
        
        return true;
    }

    isValidKingMove(piece, targetX, targetY) {
        const dx = Math.abs(targetX - piece.x);
        const dy = Math.abs(targetY - piece.y);
        
        // 将/帅走一格直线
        if ((dx === 1 && dy === 0) || (dx === 0 && dy === 1)) {
            // 限制在九宫格内
            if (targetX < 3 || targetX > 5) return false;
            if (piece.color === 'red' && (targetY < 7 || targetY > 9)) return false;
            if (piece.color === 'black' && (targetY < 0 || targetY > 2)) return false;
            return true;
        }
        return false;
    }

    isValidCannonMove(piece, targetX, targetY) {
        // 炮走直线
        if (targetX !== piece.x && targetY !== piece.y) return false;
        
        const targetPiece = this.pieces.find(p => p.x === targetX && p.y === targetY);
        let pieceCount = 0;
        
        // 计算路径上的棋子数量
        if (targetX === piece.x) {
            // 竖直移动
            const minY = Math.min(piece.y, targetY);
            const maxY = Math.max(piece.y, targetY);
            for (let y = minY + 1; y < maxY; y++) {
                if (this.pieces.some(p => p.x === piece.x && p.y === y)) {
                    pieceCount++;
                }
            }
        } else {
            // 水平移动
            const minX = Math.min(piece.x, targetX);
            const maxX = Math.max(piece.x, targetX);
            for (let x = minX + 1; x < maxX; x++) {
                if (this.pieces.some(p => p.x === x && p.y === piece.y)) {
                    pieceCount++;
                }
            }
        }
        
        // 炮的移动规则：
        // 1. 如果目标位置没有棋子，中间不能有棋子
        // 2. 如果要吃子，中间必须只有一个棋子
        return targetPiece ? pieceCount === 1 : pieceCount === 0;
    }

    isValidPawnMove(piece, targetX, targetY) {
        const dx = Math.abs(targetX - piece.x);
        const dy = targetY - piece.y;
        
        if (piece.color === 'red') {
            // 红方兵
            if (dy > 0) return false; // 不能后退
            if (piece.y > 4) {
                // 未过河，只能前进
                return dx === 0 && dy === -1;
            } else {
                // 过河后，可以横着走或向前
                return (dx === 0 && dy === -1) ||  // 向前走
                       (dy === 0 && dx === 1);     // 横向走（左或右一格）
            }
        } else {
            // 黑方卒
            if (dy < 0) return false; // 不能后退
            if (piece.y < 5) {
                // 未过河，只能前进
                return dx === 0 && dy === 1;
            } else {
                // 过河后，可以横着走或向前
                return (dx === 0 && dy === 1) ||   // 向前走
                       (dy === 0 && dx === 1);     // 横向走（左或右一格）
            }
        }
    }

    // 添加状态更新方法
    updateStatus() {
        if (this.gameOver) {
            this.statusDiv.textContent = `游戏结束！${this.winner === 'red' ? '红方' : '黑方'}获胜！`;
            this.statusDiv.style.color = this.winner === 'red' ? '#c40d0d' : '#000';
        } else {
            this.statusDiv.textContent = `当前回合：${this.currentPlayer === 'red' ? '红方' : '黑方'}`;
            this.statusDiv.style.color = this.currentPlayer === 'red' ? '#c40d0d' : '#000';
        }
    }

    // 修改 restart 方法
    restart() {
        this.gameOver = false;
        this.winner = null;
        this.currentPlayer = 'red';
        this.selectedPiece = null;
        
        // 重置棋子位置
        this.pieces = [
            // 红方(下方)
            { type: '车', color: 'red', x: 0, y: 9 },
            { type: '马', color: 'red', x: 1, y: 9 },
            { type: '相', color: 'red', x: 2, y: 9 },
            { type: '仕', color: 'red', x: 3, y: 9 },
            { type: '帅', color: 'red', x: 4, y: 9 },
            { type: '仕', color: 'red', x: 5, y: 9 },
            { type: '相', color: 'red', x: 6, y: 9 },
            { type: '马', color: 'red', x: 7, y: 9 },
            { type: '车', color: 'red', x: 8, y: 9 },
            { type: '炮', color: 'red', x: 1, y: 7 },
            { type: '炮', color: 'red', x: 7, y: 7 },
            { type: '兵', color: 'red', x: 0, y: 6 },
            { type: '兵', color: 'red', x: 2, y: 6 },
            { type: '兵', color: 'red', x: 4, y: 6 },
            { type: '兵', color: 'red', x: 6, y: 6 },
            { type: '兵', color: 'red', x: 8, y: 6 },
            
            // 黑方(上方)
            { type: '车', color: 'black', x: 0, y: 0 },
            { type: '马', color: 'black', x: 1, y: 0 },
            { type: '象', color: 'black', x: 2, y: 0 },
            { type: '士', color: 'black', x: 3, y: 0 },
            { type: '将', color: 'black', x: 4, y: 0 },
            { type: '士', color: 'black', x: 5, y: 0 },
            { type: '象', color: 'black', x: 6, y: 0 },
            { type: '马', color: 'black', x: 7, y: 0 },
            { type: '车', color: 'black', x: 8, y: 0 },
            { type: '炮', color: 'black', x: 1, y: 2 },
            { type: '炮', color: 'black', x: 7, y: 2 },
            { type: '卒', color: 'black', x: 0, y: 3 },
            { type: '卒', color: 'black', x: 2, y: 3 },
            { type: '卒', color: 'black', x: 4, y: 3 },
            { type: '卒', color: 'black', x: 6, y: 3 },
            { type: '卒', color: 'black', x: 8, y: 3 }
        ];
        
        // 重绘棋盘
        this.drawBoard();
        this.drawPieces();
        this.updateStatus();
    }
}

// 初始化棋盘
window.onload = () => {
    new ChessBoard();
}; 